/**
 * 
 */
package galacticthrone.screen.text;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.IntBuffer;

import galacticthrone.main.GTGame;

import javax.imageio.ImageIO;
import javax.media.opengl.GL;

import org.apache.log4j.Logger;

import javagame.core.io.video.texture.Texture;
import javagame.core.main.Game;

// TODO Javadoc
/**
 * 
 *
 * @author Jaco van der Westhuizen
 */
public class BitmapFontTexture implements Texture
{
	private static final Logger logger = Logger.getLogger(BitmapFontTexture.class);

	final int[] index = new int[1];
	final int width;
	final int height;

	BitmapFontTexture(String fileName)
	{
		this(GTGame.get().grabGL(), fileName);

		GTGame.get().releaseGL();
	}

	BitmapFontTexture(GL gl, String fileName)
	{
		BufferedImage img = null;
		try
		{
			img = ImageIO.read(new File(fileName));
		}
		catch (IOException x)
		{
			logger.error("Could not load bitmap font '" + fileName + "'", x);
		}
		
		if (img == null)
		{
			width = 0;
			height = 0;
			return;
		}

		width = img.getWidth();
		height = img.getHeight();
		final int[] pixels = new int[width * height];
		img.getRGB(0, 0, width, height, pixels, 0, width);

		for (int i = 0; i < pixels.length; i++)
		{
			final int c = pixels[i];
			pixels[i] = ((c >> 24) & 0xff) | ((c & 0xffffff) << 8);
		}
		
		gl.glGenTextures(1, index, 0);
        gl.glBindTexture(GL.GL_TEXTURE_2D, index[0]);
        gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR);
        gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
        gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_GENERATE_MIPMAP, GL.GL_TRUE);
        gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, width, height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_INT_8_8_8_8, IntBuffer.wrap(pixels));
	}

	/* (non-Javadoc)
	 * @see javagame.core.io.video.texture.Texture#activate(javax.media.opengl.GL)
	 */
	@Override
	public void activate(GL gl)
	{
        gl.glBindTexture(GL.GL_TEXTURE_2D, index[0]);
	}

	/* (non-Javadoc)
	 * @see javagame.core.io.video.texture.Texture#getHeight()
	 */
	@Override
	public int getHeight()
	{
		return height;
	}

	/* (non-Javadoc)
	 * @see javagame.core.io.video.texture.Texture#getWidth()
	 */
	@Override
	public int getWidth()
	{
		return width;
	}

	/* (non-Javadoc)
	 * @see javagame.core.io.video.texture.Texture#unload(javax.media.opengl.GL)
	 */
	@Override
	public void unload(GL gl)
	{
		gl.glDeleteTextures(1, index, 0);
	}

	/* (non-Javadoc)
     * @see java.lang.Object#finalize()
     */
    @Override
    protected void finalize() throws Throwable
    {
	    GL gl = Game.get().grabGL();
	    unload(gl);
	    Game.get().releaseGL();

	    super.finalize();
    }
}
